package com.commerceE.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.commerceE.common.exception.ServiceException;
import com.commerceE.dao.DictCityDao;
import com.commerceE.dao.DictProvinceDao;
import com.commerceE.domain.Address;
import com.commerceE.domain.Category;
import com.commerceE.domain.DictCity;
import com.commerceE.domain.DictProvince;
import com.commerceE.domain.Product_instance;
import com.commerceE.domain.Products;
import com.commerceE.domain.User;
import com.commerceE.service.AddressService;
import com.commerceE.service.CategoryService;
import com.commerceE.service.ProductInstanceService;
import com.commerceE.service.ProductService;

@SessionAttributes({"currentUser"})
@Controller
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
	
	@Autowired
	private ProductService productService;

	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ProductInstanceService productInstanceService;
	
	@Autowired
	private AddressService addressService;
	
	@Autowired
	private DictProvinceDao dictProvinceDao;
	
	@Autowired
	private DictCityDao dictCityDao;
	
	
	@ModelAttribute("currentUser")
	public User initCurrentUser(Model model) {
		Object user = RequestContextHolder.currentRequestAttributes().getAttribute("currentUser", RequestAttributes.SCOPE_SESSION);
		if(user!=null){
			return (User)user;
		}else{
		    return User.createInitalUser(); 
		}
    }

	
	@RequestMapping(value = "/addToCart", method = RequestMethod.POST)
	public @ResponseBody Map<String,String> addToCart(@ModelAttribute("currentUser")User currentUser,Long productId,
			Long sizeId, Long colorId, Integer quantity, Model model){
		 Map<String,String> map = new HashMap<String,String>();
		 Product_instance productInstance = productInstanceService.getProductInstanceByProductIdAndColorAndSize(productId, 
				 colorId, sizeId);
		 if(productInstance==null){
			 map.put("error", "对不起，改产品不能被找到。");
			 return map;
		 }
		 if(quantity==0){
			 map.put("error", "对不起，请您选择产品数量。");
			 return map;
		 }
		 List<Product_instance> productInstanceListOfSession = currentUser.getProductInstanceListOfSession();
		 boolean flag = false;
		 double totalPrice = quantity * productInstance.getProduct().getDiscountPrice();
		 int totalQuantity = quantity;
		 for(Product_instance pi : productInstanceListOfSession){
			 totalPrice = totalPrice + pi.getQuantity() * pi.getProduct().getDiscountPrice();
			 totalQuantity = totalQuantity + pi.getQuantity();
			 if(pi.getProductId()==productInstance.getProductId() && pi.getColorId()==productInstance.getColorId()
					 && pi.getSizeId()==productInstance.getSizeId()){
				 pi.setQuantity(pi.getQuantity()+quantity);
				 flag = true;
			 }
		 }
		 if(!flag){
			 productInstance.setQuantity(quantity);
			 productInstanceListOfSession.add(productInstance);
		 }
		 currentUser.setTotalPrice(totalPrice);
		 currentUser.setTotalQuantity(totalQuantity);
		 map.put("success", "您已经成功的添加了"+quantity+"件产品<a>"+ productInstance.getProduct().getProductName() +"</a>到购物车!");
		 map.put("total", totalQuantity+"件商品 - <strong>¥"+totalPrice +"</strong>.");
		 return map;
	}
	
	@RequestMapping(value = "/topShoppingCart", method = {RequestMethod.POST,RequestMethod.GET})
	public String topShoppingCart(@ModelAttribute("currentUser")User currentUser, Long productId, Model model){
		return "topShoppingCart";
	}
	
	@RequestMapping(value = "", method = {RequestMethod.POST,RequestMethod.GET})
	public String shoppingCart(@ModelAttribute("currentUser")User currentUser, Long productId, Model model){
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		return "shoppingCart";
	}
	
	@RequestMapping(value = "updateShoppingCartQuantity", method = {RequestMethod.POST,RequestMethod.GET})
	public String updateShoppingCartQuantity(@ModelAttribute("currentUser")User currentUser, Long productInstanceId, Integer quantity, Model model){
		List<Product_instance> productInstanceListOfSession = currentUser.getProductInstanceListOfSession();
		for(Product_instance pi : productInstanceListOfSession){
			if(pi.getProductInstanceId()==productInstanceId){
				pi.setQuantity(quantity);
				break;
			}
		 }
		double totalPrice = 0;
		int totalQuantity = 0;
		for(Product_instance pi : productInstanceListOfSession){
			totalPrice = totalPrice + pi.getQuantity()*pi.getProduct().getDiscountPrice();
			totalQuantity = totalQuantity +pi.getQuantity();
		}
		currentUser.setTotalPrice(totalPrice);
		currentUser.setTotalQuantity(totalQuantity);
		
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		return "shoppingCart";
	}
	
	@RequestMapping(value = "deleteFromShoppingCart", method = {RequestMethod.POST,RequestMethod.GET})
	public String deleteFromShoppingCart(@ModelAttribute("currentUser")User currentUser, Long productInstanceId, Model model){
		List<Product_instance> productInstanceListOfSession = currentUser.getProductInstanceListOfSession();
		for(Product_instance pi : productInstanceListOfSession){
			if(pi.getProductInstanceId()==productInstanceId){
				productInstanceListOfSession.remove(pi);
				break;
			}
		 }
		double totalPrice = 0;
		int totalQuantity = 0;
		for(Product_instance pi : productInstanceListOfSession){
			totalPrice = totalPrice + pi.getQuantity()*pi.getProduct().getDiscountPrice();
			totalQuantity = totalQuantity +pi.getQuantity();
		}
		currentUser.setTotalPrice(totalPrice);
		currentUser.setTotalQuantity(totalQuantity);
		
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		return "shoppingCart";
	}
	
	@RequestMapping(value = "checkout_login", method = {RequestMethod.POST,RequestMethod.GET})
	public String checkout_login(@ModelAttribute("currentUser")User currentUser, Model model){
		if(User.validateCurrentUser(currentUser)){
			return "redirect:/shoppingCart/checkout.html";
		}
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		model.addAttribute("user",new User());
		return "checkout_login";
	}
	
	@RequestMapping(value = "checkout", method = {RequestMethod.POST,RequestMethod.GET})
	public String checkout(@ModelAttribute("currentUser")User currentUser, Model model){
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		model.addAttribute("user",new User());
		return "checkout";
	}
	
	@RequestMapping(value = "addressList", method = {RequestMethod.GET})
	public String addressList(@ModelAttribute("currentUser")User currentUser,Model model){
		List<Address> addressList = null;
		List<DictProvince> provinceList = null;
		if(User.validateCurrentUser(currentUser)){
			addressList = addressService.getAddressByUserId(currentUser.getUserid());
		}
		
		provinceList = dictProvinceDao.getAllProvinceList();
		
		model.addAttribute("provinceList",provinceList);
		model.addAttribute("address",new Address());
		model.addAttribute("addressList",addressList);
		return "address";
	}
	
	@RequestMapping(value = "addressSubmit", method = {RequestMethod.POST})
	public String addressSubmit(@ModelAttribute("currentUser")User currentUser, Address address, BindingResult result, Model model){
		List<Address> addressList = null;
		if(User.validateCurrentUser(currentUser)){
			addressList = addressService.getAddressByUserId(currentUser.getUserid());
		}
		if(address==null){
			result.reject("error", "保存地址信息失败 ");
		}
		if(currentUser.getUserid()!=null && currentUser.getUserid()!=0){
			address.setUserid(currentUser.getUserid());
		}else{
			address.setUserid(-1L);
		}
		
		if(address.getAddressid()==null || address.getAddressid()==0){
			Date date = new Date();
			address.setCreatedtime(date);
			address.setLastupdatedtime(date);
			addressService.insertAddress(address);
		}else{
			address.setLastupdatedtime(new Date());
			addressService.updateAddress(address);
		}
		model.addAttribute("addressList",addressList);
		return "redirect:/shoppingCart/checkout.html";
	}
	
	@RequestMapping(value = "/selectCityByProvinceId", method = RequestMethod.POST)
	public @ResponseBody Map<String,String> selectCityByProvinceId(Long provinceId, Long addressId, Model model){
		 Map<String,String> map = new HashMap<String,String>();
		 
		 List<DictCity> cityList = (List<DictCity>)dictCityDao.getCityListByProvinceId(provinceId);
		 StringBuffer citySelectStr = new StringBuffer("&nbsp;&nbsp; <select  id='new_city_"+ addressId +"' onchange='selectCity("+addressId+")' name='city'>");
		 citySelectStr = citySelectStr.append("<option value='0'>请选择</option>");
		 for(int i=0;i<cityList.size();i++){
			 DictCity dictCity = cityList.get(i);
			 String str = "<option value='"+ dictCity.getCityid()+"'>" + dictCity.getCityname() + "</option>";
			 citySelectStr = citySelectStr.append(str);
		 }
		 citySelectStr = citySelectStr.append("</select>");
		 map.put("success","true");
		 map.put("citys", citySelectStr.toString());
		 return map;
	} 

	
	public ProductInstanceService getProductInstanceService() {
		return productInstanceService;
	}


	public void setProductInstanceService(
			ProductInstanceService productInstanceService) {
		this.productInstanceService = productInstanceService;
	}


	public AddressService getAddressService() {
		return addressService;
	}


	public void setAddressService(AddressService addressService) {
		this.addressService = addressService;
	}


	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}


	public DictProvinceDao getDictProvinceDao() {
		return dictProvinceDao;
	}


	public void setDictProvinceDao(DictProvinceDao dictProvinceDao) {
		this.dictProvinceDao = dictProvinceDao;
	}


	public DictCityDao getDictCityDao() {
		return dictCityDao;
	}


	public void setDictCityDao(DictCityDao dictCityDao) {
		this.dictCityDao = dictCityDao;
	}
	
	
}
